package com.thinkgem.jeesite.modules.KDniao.web;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.thinkgem.jeesite.common.web.BaseController;
import com.thinkgem.jeesite.modules.KDniao.entity.LogisticTrackingTrajectory;
import com.thinkgem.jeesite.modules.KDniao.entity.LogisticsThreeParty;
import com.thinkgem.jeesite.modules.KDniao.entity.KDniaorequestMe.RequestApplicationParameters;
import com.thinkgem.jeesite.modules.KDniao.entity.KDniaorequestMe.RequestDate;
import com.thinkgem.jeesite.modules.KDniao.entity.KDniaorequestMe.ResponesResult;
import com.thinkgem.jeesite.modules.KDniao.service.logistics.LogisticTrackingTrajectoryService;
import com.thinkgem.jeesite.modules.KDniao.service.logistics.LogisticsThreePartyService;
import com.thinkgem.jeesite.modules.KDniao.unit.CacheUtils;
import com.thinkgem.jeesite.modules.KDniao.unit.KDnaioUnit;

@Controller
@RequestMapping(value = "logistics/requestme")
public class KDniaoRequestMe extends BaseController {
    @Autowired
    private KDnaioUnit kDnaioUnit;

    @Autowired
    private LogisticsThreePartyService logisticsThreePartyService;

    private static String EBusinessID = "1283015";

    @Autowired
    private LogisticTrackingTrajectoryService logisticTrackingTrajectoryService;

    /**
     * 提供给快递鸟
     * 
     * @param request
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "logistics", produces = "application/x-www-form-urlencoded;charset=utf-8", method = RequestMethod.POST)
    @ResponseBody
    public Object logistics(HttpServletRequest request) throws Exception {
        String RequestData = request.getParameter("RequestData");
        String DataSign = request.getParameter("DataSign");
        String RequestType = request.getParameter("RequestType");
        if(RequestData==null || "".equals(RequestData)){
            logger.warn("数据内容为空");
            return getResponesResult("数据内容为空", "110",false);
        }

        if (DataSign == null || "".equals(DataSign)) {
            logger.warn("签名为空");
            return getResponesResult("签名为空", "110",false);
        }
        if (RequestType == null || "".equals(RequestType)) {
            logger.warn("类型为空");
            return getResponesResult("类型为空", "110",false);
        }
        RequestData = decode(RequestData);
        boolean fals = sign(DataSign, RequestData);
        if (!fals) {
            logger.warn("签名失败");
            return getResponesResult("签名失败", "110", false);
        }
        //轨迹跟踪信息
        if ("101".equals(RequestType)) {
            updateTrackingTrajectory(RequestData);
        }
        //货款状态信息
        if ("107".equals(RequestType)) {

        }
        logger.warn(getResponesResult(null, EBusinessID, true));
        return getResponesResult(null, EBusinessID, true);
    }

    //返回数据
    private String getResponesResult(String reason, String id, boolean Success) throws JsonProcessingException {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:ss:mm");
        ResponesResult responesResult = new ResponesResult();
        responesResult.setEbusinessID(id);
        responesResult.setReason(reason);
        responesResult.setSuccess(Success);
        responesResult.setUpdateTime(dateFormat.format(new Date()));
        ObjectMapper mapper = getJsonMapper();
        return mapper.writeValueAsString(responesResult);
    }

    private ObjectMapper getJsonMapper() {
        return new ObjectMapper();
    }

    private String decode(String decode) {
        try {
            return URLDecoder.decode(decode, "utf-8");
        } catch (UnsupportedEncodingException e) {
        }
        return decode;
    }

    @SuppressWarnings("unchecked")
    private List<LogisticsThreeParty> getLogisticsThreeParty() {
        List<LogisticsThreeParty> lks = (List<LogisticsThreeParty>) CacheUtils.get("LogisticsThreePartyisenadleallListDesc");
        logger.info("快递鸟配置缓存" + lks);
        if (lks == null || lks.size() == 0) {
            lks = logisticsThreePartyService.findAllbyDesc();
            CacheUtils.put("LogisticsThreePartyisenadleallListDesc", lks);
            logger.info("快递鸟配置缓存成功" + lks);
        }
        return lks;
    }

    private synchronized void updateTrackingTrajectory(String RequestData) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:ss:mm");
        SimpleDateFormat dateFormat2 = new SimpleDateFormat("yyyy-MM-dd");
        ObjectMapper mapper = getJsonMapper();
        try {
	    logger.info("接收到快递鸟的数据" + RequestData);
            RequestApplicationParameters applicationParameters = mapper.readValue(RequestData, RequestApplicationParameters.class);
            List<RequestDate> list = applicationParameters.getData();
            for (int i = 0; i < list.size(); i++) {
                RequestDate requestDate = list.get(i);
                //获得订阅物流信息保存轨迹
                List<LogisticTrackingTrajectory> logisticTrackingTrajectorys = getlogisticTrackingTrajectory(requestDate);
                //保存轨迹
                for (int j = 0; j < logisticTrackingTrajectorys.size(); j++) {
                    LogisticTrackingTrajectory logisticTrackingTrajectory = logisticTrackingTrajectorys.get(j);
                    logger.info(logisticTrackingTrajectory.getId() + "===========" + logisticTrackingTrajectorys.size());
                if (logisticTrackingTrajectory != null) {

                    if (requestDate.getEstimatedDeliveryTime() != null) {
                        try {
                            logisticTrackingTrajectory.setEstimateddeliverytime(dateFormat.parse(requestDate.getEstimatedDeliveryTime()));
                        } catch (ParseException e) {
                            try {
                                logisticTrackingTrajectory.setEstimateddeliverytime(dateFormat2.parse(requestDate.getEstimatedDeliveryTime()));
                            } catch (ParseException e1) {
                            }

                        }
                    }
                    if (applicationParameters.getPushTime() != null) {
                        try {
                            logisticTrackingTrajectory.setPushtime(dateFormat.parse(applicationParameters.getPushTime()));
                        } catch (ParseException e) {
                            try {
                                logisticTrackingTrajectory.setPushtime(dateFormat2.parse(applicationParameters.getPushTime()));
                            } catch (ParseException e1) {
                            }

                        }
                    }
			String json = mapper.writeValueAsString(requestDate);
			logger.info("接收并保存的数据" + json);
			logisticTrackingTrajectory.setDatas(json);
			logisticTrackingTrajectory.setCreatetime(new Date());
			logisticTrackingTrajectoryService.save(logisticTrackingTrajectory);
			logger.info("保存成功！" + json);
                }
              }
            }
            
        } catch (JsonParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (JsonMappingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }

    /**
     * 获得订阅物流信息保存轨迹
     * 
     * @param requestDate
     * @return
     */
    private List<LogisticTrackingTrajectory> getlogisticTrackingTrajectory(RequestDate requestDate) {
        logger.info(
                "ShipperCode()=" + requestDate.getShipperCode() + "====LogisticCode=====" + requestDate.getLogisticCode() + "==OrderCode==========="
                        + requestDate.getOrderCode());
        LogisticTrackingTrajectory logisticTrackingTrajectory = new LogisticTrackingTrajectory();
        logisticTrackingTrajectory.setShippercode(requestDate.getShipperCode());
        logisticTrackingTrajectory.setLogisticcode(requestDate.getLogisticCode());
        logisticTrackingTrajectory.setOrdercode(requestDate.getOrderCode());
        //设置回调函数时其值为订单。接口会返回回调值
        if ("".equals(requestDate.getOrderCode()) || requestDate.getOrderCode() == null) {
            if (!"".equals(requestDate.getCallBack()) && requestDate.getCallBack() != null) {
                logisticTrackingTrajectory.setOrdercode(requestDate.getCallBack());
            }
        }
        List<LogisticTrackingTrajectory> logisticTrackingTrajectories = logisticTrackingTrajectoryService
                .getTrackingbyLogisticCodeandShipperCode(logisticTrackingTrajectory);
        return logisticTrackingTrajectories;
    }
    /**
     * 判断签名是否正确
     * 
     * @param datasign
     * @return
     * @throws Exception
     * @throws UnsupportedEncodingException
     */
    private boolean sign(String datasign, String RequestData) throws UnsupportedEncodingException, Exception {
        List<LogisticsThreeParty> list=getLogisticsThreeParty();
        for (int i = 0; i < list.size(); i++) {
            LogisticsThreeParty logisticsThreeParty = list.get(i);
            String mysign = kDnaioUnit.encrypt(RequestData, logisticsThreeParty.getAppkey(), "utf-8");
            if (datasign.equals(mysign)) {
                EBusinessID = logisticsThreeParty.getEbusinessid();
                return true;
            }
        }
        return false;
    }

}
